import cgi
import wsgiref.handlers
import os
import datetime

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

from listmodel import ListModel
import utils

class MainRequestHandler( webapp.RequestHandler ):
    def get( self ):
        # Creating an empty Template Input Values dictionary
        template_input_values = utils.buildLoginbarTemplateInputValues(self)
        
        # Check if this is an Ajax Call or not. Default is not.
        ajax_call = self.request.get("ajax")
        
        # Figuring Out if there is a User logged in or not
        if ( users.get_current_user() ):            
            # Retrieving the Lists currently not complete (aka "Current Lists")
            current_lists = ListModel.gql(
                                " WHERE "
                                " owner = :owner "
                                " AND "
                                " completion_date = :completion_date "
                                " ORDER BY creation_date DESC",
                                owner = users.get_current_user(),
                                completion_date = None)
            
# TO REMEMBER - REMOVEME            
#        template_input_values['current_lists'] = []
#        template_input_values['current_lists'].append({'percentage' : 73, 
#                                                  'percentage_normalized' : 50,
#                                                  'items_num' : 15,
#                                                  'items_left' : 8,
#                                                  'title' : "Things to do when Alessandra will be Here",
#                                                  'description' : "One thing that is implicit: to remind her how much I love her. This is the only thing that is sure in my life: you, your love for me and my love for you..",
#                                                  'creation_date' : datetime.date.today(),
#                                                  'tags' : ["test", "love", "personal", "things", "todo"],
#                                                  'visibility' : "shared",
#                                                  'sharers' : ["alessandra.simola@gmail.com", "ivan.de.marino@gmail.com"]})
# TO REMEMBER - REMOVEME END
            
            # Building the Current Lists parameters
            template_input_values['current_lists'] = []
            for current_list in current_lists:
                template_input_values['current_lists'].append({'percentage' : 73, # TODO 
                                                  'percentage_normalized' : 50, # TODO
                                                  'items_num' : 15, # TODO
                                                  'items_left' : 8, # TODO
                                                  'id' : current_list.key().id(),
                                                  'title' : current_list.title,
                                                  'description' : current_list.description,
                                                  'creation_date' : current_list.creation_date,
                                                  'tags' : current_list.tags,
                                                  'visibility' : current_list.visibility})

# TO REMEMBER - REMOVEME
#        template_input_values['done_lists'] = []
#        template_input_values['done_lists'].append({'title' : "Completed Task",
#                                                    'id' : done_list.key().id(),
#                                                  'completion_date' : datetime.date.today(),
#                                                  'visibility' : "shared"})
# TO REMEMBER - REMOVEME END

            # Choose the Template based on the request of an Ajax Call or not
            if ( ajax_call and ajax_call == "true" ):
                # Loading the "main" template
                template_path = os.path.join( os.path.dirname( __file__ ), 
                                              'templates/main-current_lists_only.html' )
            else:
                # Loading the "main" template
                template_path = os.path.join( os.path.dirname( __file__ ), 
                                              'templates/main.html' )
        else:            
            # Loading the "wellcome" (not logged in) template
            template_path = os.path.join( os.path.dirname( __file__ ), 
                                          'templates/wellcome.html' )
        
        # Rendering Templates passing previously built Parameters
        self.response.out.write( template.render( template_path, template_input_values ) )

def main():
    # Creating a WSGI Application Handler
    application = webapp.WSGIApplication([
                                          ( '/', MainRequestHandler )
                                          ], debug=True )
    # Executing the WSGI Application
    wsgiref.handlers.CGIHandler().run( application )

if __name__ == "__main__":
    main()
